import javax.swing.tree.TreeNode;


public class Solution {
    static class TreeNode {
        public int val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(int val) {
            this.val = val;
        }
    }


        public int posIndex = 0;

        public TreeNode buildTree(int[] inorder, int[] postorder) {
            posIndex = postorder.length - 1;
            return buildTreeChild(inorder, 0, inorder.length - 1, postorder);
        }

        public int findval(int[] inorder, int inbegin, int inend, int key) {
            for (int i = inbegin; i <= inend; i++) {
                if (inorder[i] == key) {
                    return i;
                }
            }
            return -1;
        }

        public TreeNode buildTreeChild(int[] inorder, int inbegin, int inend, int[] postorder) {
            if (inbegin > inend) {
                return null;
            }
            TreeNode root = new TreeNode(postorder[posIndex]);
            int mind = findval(inorder, inbegin, inend, postorder[posIndex]);
            posIndex--;

            root.right = buildTreeChild(inorder, mind + 1, inend, postorder);
            root.left = buildTreeChild(inorder, inbegin, mind - 1, postorder);

            return root;
        }
    }

